package com.fancy.learncenter.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonContructSatisticsesBean;
import com.fancy.learncenter.bean.CartoonErrorUnitListBean;
import com.fancy.learncenter.bean.CartoonErrorUnitListItemBean;
import com.fancy.learncenter.bean.CartoonHomeworkContructSatisticsesBean;
import com.fancy.learncenter.bean.CartoonPreviewStaticHomeworkBean;
import com.fancy.learncenter.bean.CartoonQuestionBankBean;
import com.fancy.learncenter.bean.CartoonQuestionIdsBean;
import com.fancy.learncenter.bean.CartoonQuestionIdsItemBean;
import com.fancy.learncenter.bean.CartoonStudentStatisBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.adapter.CartoonHomeworkContentAdapter;
import com.fancy.learncenter.ui.callback.AlbumImpl;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.PermissionHelper;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 预览作业列表
 */
public class PreviewHomeWorkActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.right)
    TextView right;
    @Bind(R.id.right_img)
    ImageView rightImg;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.lesson_name_text)
    TextView lessonNameText;
    @Bind(R.id.unit_name_text)
    TextView unitNameText;
    @Bind(R.id.duration_text)
    TextView durationText;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    private CartoonHomeworkContentAdapter adapter;
    private List<CartoonHomeworkContructSatisticsesBean> list = new ArrayList<>();
    private Gson gson = new Gson();
    private String homePackageId;
    private String unitId;
    private String classId;
    private ArrayList<QuestionVOsBean> questionOriginList = new ArrayList<>();
    private ArrayList<QuestionVOsBean> questionArrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_home_work, Status.STATUS);
        ButterKnife.bind(this);

        initToolbar("作业预览");
        getIntentData();
        initQuestionListData();
        initRecycleView();
        cartoonListHomeworkStatistic();
//        getStaticsData();
    }

    private void getIntentData() {
//        studentHomeworkId = getIntent().getStringExtra(JumpIntentKey.STUDENTHOMEWORKID);
        homePackageId = getIntent().getStringExtra(JumpIntentKey.HOMEWORK_PACKAGE_ID);
        unitId = getIntent().getStringExtra(JumpIntentKey.UNIT_ID);
        classId = getIntent().getStringExtra(JumpIntentKey.CLASSID);
    }

    private void initRecycleView() {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new CartoonHomeworkContentAdapter(this, list);
        recyclerView.setAdapter(adapter);
        adapter.setListener(new AlbumImpl() {
            @Override
            public void onClick(int position) {

                String constructId = list.get(position).getConstructId();
                List<String> questionIds = list.get(position).getQuestionIds();
                dataUtils(questionIds);
//                getErrorKindsByIdData(constructId);
            }
        });

    }

    private void dataUtils(List<String> questionIds) {
        questionArrayList.clear();
        for (String itemBean : questionIds) {
            for (QuestionVOsBean vOsBean : questionOriginList) {
                if (String.valueOf(vOsBean.getQuestionId()).equals(itemBean)) {
                    questionArrayList.add(vOsBean);
                    break;
                }
            }
        }
        if (questionArrayList.size() > 0) {
            homePackageId = questionArrayList.get(0).getHomeworkPackageId();
        }

        Intent intent = new Intent(PreviewHomeWorkActivity.this, TeacherPreviewHomeworkActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
        bundle.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, questionArrayList);
        intent.putExtras(bundle);
        startActivity(intent);

    }


    private void cartoonListHomeworkStatistic() {

        Map<String, Object> map = new HashMap<>();
        map.put("homeworkPackageId", homePackageId);
        HttpMehtod.getInstance().cartoonListHomeworkStatistic(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonPreviewStaticHomeworkBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonPreviewStaticHomeworkBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonPreviewStaticHomeworkBean>() {
                    @Override
                    public void success(CartoonPreviewStaticHomeworkBean dataBean) {

                        if (dataBean != null) {
                            CartoonPreviewStaticHomeworkBean.ResultBean resultBean = dataBean.getResult();
                            if (resultBean != null) {
                                if (!TextUtils.isEmpty(resultBean.getLessonName())) {
                                    lessonNameText.setText(resultBean.getLessonName());
                                }
                                if (!TextUtils.isEmpty(resultBean.getUnitName())) {
                                    unitNameText.setText(resultBean.getUnitName());
                                }
                                list.addAll(resultBean.getHomeworkContructSatisticses());
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();


            }
        });

    }


    /**
     * 根据id
     */
    private void getErrorKindsByIdData(String constructId) {
        questionArrayList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("constructId", constructId);
        map.put("unitId", unitId);
        map.put("classId", classId);
        HttpMehtod.getInstance().cartoonListConstructId(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                dataUtils(responseBodyResponse);
            }
        });

    }

    private void dataUtils(Response<ResponseBody> responseBodyResponse) {
        BaseBean<CartoonQuestionIdsBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonQuestionIdsBean.class);

        CustomNetCallBack callBack = new CustomNetCallBack(this, baseBean);
        callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonQuestionIdsBean>() {
            @Override
            public void success(CartoonQuestionIdsBean dataBean) {


                List<CartoonQuestionIdsItemBean> idsItemBeanList = dataBean.getObjectQuestionIds();
                if (idsItemBeanList != null && idsItemBeanList.size() > 0) {
                    String fileName = Constant.CARTOON_QUESTION_BANK + String.valueOf(LoginUserSharePrefernce.getCustomId() + "_" + homePackageId) + ".td";
//                    if (!FileUtils.checKFileExists(fileName)) {
//                        downloadWork(fileName);
//                    } else {

//                        Gson gson = new Gson();
//                        String readResultStr = FileUtils.readFromSD(fileName);
//                        CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
//                        ArrayList<QuestionVOsBean> tempQuestionArrayList = new ArrayList<>();
//                        tempQuestionArrayList.addAll(questionBankBean1.getQuestionVOs());

                    for (CartoonQuestionIdsItemBean itemBean : idsItemBeanList) {
                        for (QuestionVOsBean vOsBean : questionOriginList) {
                            if (String.valueOf(vOsBean.getQuestionId()).equals(itemBean.getObjectQuestionId())) {
                                questionArrayList.add(vOsBean);
                                break;
                            }
                        }
                    }
                    if (questionArrayList.size() > 0) {
                        homePackageId = questionArrayList.get(0).getHomeworkPackageId();
                    }

                    Intent intent = new Intent(PreviewHomeWorkActivity.this, TeacherPreviewHomeworkActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
                    bundle.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, questionArrayList);
                    intent.putExtras(bundle);
                    startActivity(intent);

//                    }
                } else {
//                    ToastUtil.show("  暂无错题");
//                    finish();
                }

            }

            @Override
            public void fail(String errorCode) {

            }
        }).dealData();
    }


    private void initQuestionListData() {

        String fileName = Constant.CARTOON_QUESTION_BANK + String.valueOf(LoginUserSharePrefernce.getCustomId() + "_" + homePackageId) + ".td";
//        if (!FileUtils.checKFileExists(fileName)) {
//
//            downloadWork(fileName);
//
//        } else {
//            String readResultStr = FileUtils.readFromSD(fileName);
//            CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
//            questionOriginList.addAll(questionBankBean1.getQuestionVOs());
//        }

        downloadWork(fileName);

    }

    /**
     * 下载作业包
     *
     * @param fileName
     */
    private void downloadWork(final String fileName) {
        Map<String, Object> map = new HashMap<>();
        map.put("homeworkPackageId", homePackageId);
        HttpMehtod.getInstance().cartoonTeacherDownLoadHomeworkById(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonQuestionBankBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonQuestionBankBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonQuestionBankBean>() {
                    @Override
                    public void success(CartoonQuestionBankBean dataBean) {

                        String str = gson.toJson(dataBean);

                        FileUtils.creatFile(fileName);
                        FileUtils.saveStringToFile(fileName, str);
                        String readResultStr = FileUtils.readFromSD(fileName);
                        CartoonQuestionBankBean questionBankBean1 = gson.fromJson(readResultStr, CartoonQuestionBankBean.class);
                        questionOriginList.addAll(questionBankBean1.getQuestionVOs());
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }


}
